<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { graphic } from "echarts/core";

// 模拟数据
const alarmData = ref([
  { type: "R_LOS", count: 182 },
  { type: "MUT_LOS", count: 95 },
  { type: "IN_PWR_HIGH", count: 89 },
  { type: "OTU4_LOF", count: 85 },
  { type: "OSC_LOS", count: 10 },
  { type: "IN_PWR_LOW", count: 15 },
  { type: "ODUFLEX_LOFLOM", count: 11 },
  { type: "OTUCN_LOF", count: 15 },
  { type: "ODU2_LOFLOM", count: 18 },
  { type: "OA_LOW_GAIN", count: 2 },
  { type: "NE_COMMU_BREAK", count: 86 },
  { type: "GNE_CONNECT_FAIL", count: 38 },
  { type: "NE_NOT_LOGIN", count: 106 },
  { type: "设备离线", count: 4 },
  { type: "BP_ODU_LOFLOM", count: 1 },
  { type: "ODU4_LOFLOM", count: 3 },
  { type: "LSR_NO_FITED", count: 2 },
  { type: "NEBD_XC_DIF", count: 28 },
  { type: "ETH_LOS", count: 2 },
  { type: "OTU4_LOF", count: 2 },
]);

// 分页配置
const pages = ref([
  alarmData.value.slice(0, 6),
  alarmData.value.slice(6, 12),
  alarmData.value.slice(12, 17),
]);

const currentPage = ref(0);
const option = ref({});
let intervalId = null;

const updateChart = () => {
  const currentData = pages.value[currentPage.value];
  const xData = currentData.map(item => item.type);
  const yData = currentData.map(item => item.count);

  option.value = {
    xAxis: {
      type: "category",
      data: xData,
      axisLabel: {
        color: "#7EB7FD",
        fontWeight: "500",
        rotate: 45, // 旋转标签以防重叠
        interval: 0
      },
      axisLine: {
        lineStyle: { color: "rgba(31,99,163,.1)" }
      }
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: { color: "rgba(31,99,163,.2)" }
      },
      axisLabel: {
        color: "#7EB7FD",
        fontWeight: "500"
      }
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0,0,0,.6)",
      borderColor: "rgba(147, 235, 248, .8)",
      textStyle: { color: "#FFF" }
    },
    grid: {
      left: "10px",
      right: "30px",
      bottom: "40px", // 增加底部空间以容纳旋转标签
      top: "32px",
      containLabel: true
    },
    series: [
      {
        data: yData,
        type: "bar",
        name: "告警次数",
        barWidth: "60%",
        itemStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(9,202,243,.7)" },
            { offset: 1, color: "rgba(9,202,243,.3)" }
          ])
        }
      }
    ]
  };
};

const startCarousel = () => {
  intervalId = setInterval(() => {
    currentPage.value = (currentPage.value + 1) % pages.value.length;
    updateChart();
  }, 5000);
};

onMounted(() => {
  updateChart();
  startCarousel();
});

onUnmounted(() => {
  if (intervalId) clearInterval(intervalId);
});
</script>

<template>
  <v-chart class="chart" :option="option" v-if="JSON.stringify(option) != '{}'" />
</template>

<style scoped lang="scss">
.chart {
  width: 100%;
  height: 100%;
}
</style>
